package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.CalculateUtils;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.*;
import com.tanhua.model.vo.*;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description：test
 * @Create by： 张会豪
 * @Date：2021/11/8 0:16
 */
@Service
public class TestSoulService {

    @DubboReference
    private SoulQuestionnaireApi soulQuestionnaireApi;

    @DubboReference
    private SoulTestQuestionApi soulTestQuestionApi;

    @DubboReference
    private SoulOptionsContentApi soulOptionsContentApi;

    @DubboReference
    private SoulUserApi soulUserApi;

    @DubboReference
    private PersonalityTypeApi personalityTypeApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    //测灵魂-问卷列表
    public List<SoulQuestionVo> testSoulList() {
        List<SoulQuestionVo> vos = new ArrayList<>();
        //1、调用soulQuestionnaireApi查询soulQuestionnaire对象
        List<SoulQuestionnaire> list = soulQuestionnaireApi.findAll();
        //2、给SoulQuestionVo部分属性赋值
        if (CollUtil.isEmpty(list)) {
            return vos;
        }
        //2.1、遍历list集合
        for (SoulQuestionnaire soulQuestionnaire : list) {
            SoulQuestionVo vo = SoulQuestionVo.init(soulQuestionnaire);

            //集合遍历结束后，SoulQuestionVo中还有List<SoulTestQuestionVo>、isLock、reportId属性没赋值

            //3、构造List<SoulTestQuestionVo>集合
            List<SoulTestQuestionVo> vos1 = new ArrayList<>();
            //3.1、调用SoulTestQuestionApi根据questionnaireId查询数据
            List<SoulTestQuestion> list1 = soulTestQuestionApi.findByTypeId(soulQuestionnaire.getId());
            if (CollUtil.isEmpty(list1)) {
                return null;
            }
            //3.2、遍历list1集合
            for (SoulTestQuestion soulTestQuestion : list1) {
                SoulTestQuestionVo vo1 = SoulTestQuestionVo.init(soulTestQuestion);
                //集合遍历结束后，SoulTestQuestionVo中还有List<SoulOptionsContentVo>还没赋值

                //3.5、遍历List<SoulTestQuestionVo>集合，给List<SoulOptionsContentVo>赋值
                //3.3调用SoulOptionsContentApi查询数据
                List<SoulOptionsContentVo> vos2 = new ArrayList<>();
                List<SoulOptionsContent> list2 = soulOptionsContentApi.findById(soulTestQuestion.getId());
                if (CollUtil.isEmpty(list2)) {
                    return null;
                }
                //3.4、遍历list2
                for (SoulOptionsContent soulOptionsContent : list2) {
                    SoulOptionsContentVo vo2 = SoulOptionsContentVo.init(soulOptionsContent);
                    vos2.add(vo2);
                }
                //遍历结束，List<SoulOptionsContentVo>已经全部赋值
                vo1.setOptions(vos2);
                vos1.add(vo1);
            }
            vo.setQuestions(vos1);
            //3.6、给SoulQuestionVo中的List<SoulTestQuestionVo>赋值
            //4、设置isLock、调用api查询reportId
            SoulUser soulUser = soulUserApi.findByUserId(UserHolder.getUserId());
            if ("初级灵魂题".equals(vo.getName())) {
                vo.setIsLock(0);
                if (soulUser != null) {
                    if (soulUser.getTypeId() != null) {
                        vo.setReportId(soulUser.getTypeId().toString());
                    } else {
                        vo.setReportId(null);
                    }
                } else {
                    vo.setReportId(null);
                }
            }
            if (soulUser != null) {
                //在redis中获取数据
                String key = Constants.SOUL_TEST_UNLOCK_KEY + UserHolder.getUserId();
                if (redisTemplate.opsForHash().hasKey(key, "type2")) {
                    if ("中级灵魂题".equals(vo.getName())) {
                        vo.setIsLock(0);
                        if (redisTemplate.opsForHash().hasKey(key, "type3")) {
                            vo.setReportId(soulUser.getTypeId().toString());
                        } else {
                            vo.setReportId(null);
                        }
                    }
                }
                if (redisTemplate.opsForHash().hasKey(key, "type3")) {
                    if ("高级灵魂题".equals(vo.getName())) {
                        vo.setIsLock(0);
                        if (redisTemplate.opsForHash().hasKey(key, "type4")) {
                            vo.setReportId(soulUser.getTypeId().toString());
                        } else {
                            vo.setReportId(null);
                        }
                    }
                }
            }
            vos.add(vo);
        }
        //5、返回结果
        return vos;
    }

    //测灵魂-提交问卷
    public String submitTestSoul(Map<String, List<Map<String, Long>>> answers) throws ParseException {
        String typeId = null;
        int flag = 0;
        Long flagId = null;
        //1、接收参数
        List<Map<String, Long>> mapList = answers.get("answers");
        for (Map<String, Long> map : mapList) {
            Long questionId = map.get("questionId");//试题id
            Long optionId = map.get("optionId");//选项id
            //2、调用SoulOptionsContentApi在SoulOptionsContent表中查询对象，返回
            SoulOptionsContent soulOptionsContent = soulOptionsContentApi.findByIds(optionId, questionId);
            //3、根据当前用户id在SoulUser表中查询该用户
            SoulUser soulUser = soulUserApi.findByUserId(UserHolder.getUserId());
            if (soulUser != null) {
                //3.1、如果查询到，更新数据
                //总得分
                soulUser.setScore(CalculateUtils.numberCalculate(soulOptionsContent.getOptionScore(), soulUser.getScore()));
                //外向属性
                soulUser.setOutward(CalculateUtils.percentageCalculate(soulOptionsContent.getOutwardScore(),
                        soulUser.getOutward()));
                //判断属性
                soulUser.setVerdict(CalculateUtils.percentageCalculate(soulOptionsContent.getVerdictScore(),
                        soulUser.getVerdict()));
                //抽象属性
                soulUser.setAbstraction(CalculateUtils.percentageCalculate(soulOptionsContent.getAbstractionScore(),
                        soulUser.getAbstraction()));
                //理性属性
                soulUser.setSense(CalculateUtils.percentageCalculate(soulOptionsContent.getSenseScore(),
                        soulUser.getSense()));
                //3.1.2、调用PersonalityTypeApi根据用户总分在表中查询最新数据，返回对应人格类型id
                Long typeId1 = personalityTypeApi.findByScore(soulUser.getScore());
                //3.1.3、设值最新人格id属性
                soulUser.setTypeId(typeId1);
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(format);
                soulUser.setUpdated(date);
                //3.1.4、调用SoulUserApi进行表中数据更新
                soulUserApi.updateWithScores(soulUser);
                //3.1.5、返回结果
                typeId = String.valueOf(typeId1);
            } else {
                //3.2、如果未查询到数据，创建新的soulUser,新增到SoulUser表中
                soulUser = new SoulUser();
                soulUser.setId(UserHolder.getUserId());
                //总得分
                soulUser.setScore(soulOptionsContent.getOptionScore());
                //外向属性
                soulUser.setOutward(soulOptionsContent.getOutwardScore());
                //判断属性
                soulUser.setVerdict(soulOptionsContent.getVerdictScore());
                //抽象属性
                soulUser.setAbstraction(soulOptionsContent.getAbstractionScore());
                //理性属性
                soulUser.setSense(soulOptionsContent.getSenseScore());
                //3.2.1、调用PersonalityTypeApi根据用户总分在表中查询最新数据，返回对应人格类型id
                Long typeId1 = personalityTypeApi.findByScore(soulUser.getScore());
                //3.2.2、设值最新人格id属性
                soulUser.setTypeId(typeId1);
                //创建时间、更新时间
                String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(format);
                soulUser.setCreated(date);
                soulUser.setUpdated(date);
                //3.2.3、调用SoulUserApi进行表中数据新增
                soulUserApi.save(soulUser);
                //3.2.4、返回结果
                typeId = String.valueOf(typeId1);
            }
            flag++;
            flagId = questionId;
        }
        if (flag == 10) {
            //根据最后一次提交的id查询等级
            Long questionnaireId = soulTestQuestionApi.findById(flagId);
            //4、提交试题后，解锁下一题,存进redis
            String key = Constants.SOUL_TEST_UNLOCK_KEY + UserHolder.getUserId();
            if ((questionnaireId + 1L) == 2L) {
                String hashKey = "type2";
                redisTemplate.opsForHash().put(key, hashKey, "中级灵魂题");
            } else if ((questionnaireId + 1L) == 3L) {
                String hashKey = "type3";
                redisTemplate.opsForHash().put(key, hashKey, "高级灵魂题");
            } else if ((questionnaireId + 1L) == 4L) {
                String hashKey = "type4";
                redisTemplate.opsForHash().put(key, hashKey, "特高级灵魂题");
            }
        }
        return typeId;
    }

    //测灵魂-查看结果
    public SoulReportVo report(String id) {
        //1、接收参数，调用PersonalityTypeApi查询数据
        PersonalityType personalityType = personalityTypeApi.findById(Long.valueOf(id));
        if (personalityType == null) {
            return null;
        }
        //1.1、组装部分属性值
        SoulReportVo vo = SoulReportVo.init(personalityType);
        //2、组装List<SoulReportVoo> dimensions维度属性
        //2.1、调用SoulUserApi查询用户信息
        SoulUser soulUser = soulUserApi.findByUserId(UserHolder.getUserId());
        //2.2、开始设置维度值
        List<SoulReportVoo> voos1 = new ArrayList<>();
        if (soulUser != null) {
            if (soulUser.getOutward() != null) {
                SoulReportVoo v1 = new SoulReportVoo();
                v1.setKey("外向");
                v1.setValue(soulUser.getOutward());
                voos1.add(v1);
            }
            if (soulUser.getVerdict() != null) {
                SoulReportVoo v2 = new SoulReportVoo();
                v2.setKey("判断");
                v2.setValue(soulUser.getVerdict());
                voos1.add(v2);
            }
            if (soulUser.getAbstraction() != null) {
                SoulReportVoo v3 = new SoulReportVoo();
                v3.setKey("抽象");
                v3.setValue(soulUser.getAbstraction());
                voos1.add(v3);
            }
            if (soulUser.getSense() != null) {
                SoulReportVoo v4 = new SoulReportVoo();
                v4.setKey("理性");
                v4.setValue(soulUser.getSense());
                voos1.add(v4);
            }
        }
        vo.setDimensions(voos1);

        //2.4、根据报告id在SoulUser表中查询所有用户id
        List<Long> ids = soulUserApi.finByReportId(Long.valueOf(id));
        List<SoulReportVoo> voos2 = new ArrayList<>();
        if (CollUtil.isNotEmpty(ids)) {
            //2.3、调用UserInfo查询该用户详情
            Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
            for (Long userId : ids) {
                if (userId.equals(UserHolder.getUserId())) {
                    continue;
                }
                UserInfo userInfo = map.get(userId);
                if (userInfo != null) {
                    SoulReportVoo v5 = new SoulReportVoo();
                    v5.setId(Integer.valueOf(userId.toString()));
                    v5.setAvatar(userInfo.getAvatar());
                    voos2.add(v5);
                }
            }
        }
        //3、组装List<SoulReportVoo> similarYou属性
        vo.setSimilarYou(voos2);
        //4、返回结果
        return vo;
    }
}
